<template>
  <CollapsibleSection
    title="措施模块"
    :is-expanded="isExpanded"
    @toggle="$emit('toggle')"
  >
    <view class="space-y-[16rpx]">
      <!-- 居家护理记录 -->
      <view class="mb-[24rpx]">
        <view class="flex items-center mb-[16rpx]">
          <view class="w-[6rpx] h-[28rpx] bg-green-500 rounded-[3rpx] mr-[12rpx]"></view>
          <text class="text-[28rpx] font-bold text-gray-800">居家服务记录</text>
        </view>
        
        <ItemListManager
          :items="formData.homeCareRecords || []"
          item-title="服务记录"
          add-button-text="添加服务记录"
          add-button-color="#4caf50"
          @add="addHomeCareRecord"
          @remove="removeHomeCareRecord"
          @update="updateHomeCareRecord"
        >
          <template #default="{ item, index, update }">
            <!-- 医院部门选择器 -->
            <view class="hospital-selector" @click="() => showDirectoryPopup(index)">
              <view class="selector-content">
                <text class="selector-text">
                  {{ getSelectorText(index) }}
                </text>
                <text class="selector-arrow">▼</text>
              </view>
            </view>

            <!-- 疾病选择器 -->
            <view class="disease-selector mb-2" @click="() => showDiseasePopupHandler(index)">
              <view class="selector-content">
                <text class="selector-text">
                  {{ getDiseaseSelectorText(index) }}
                </text>
                <text class="selector-arrow">▼</text>
              </view>
            </view>

            <!-- 使用新的医院-部门-科室-项目组选择器 -->
            <HospitalDepartmentProjectSelector 
              :visible="showPopup === index" 
              @update:visible="(val) => showPopup = val ? index : false" 
              @close="closeDirectoryPopup" 
              @confirm="(data) => handleSelectorConfirm(data, index)" 
            />

            <!-- 疾病选择弹窗 -->
            <DiseaseSelector 
              :visible="showDiseasePopup === index" 
              :project-id="(item as any).projectId" 
              @update:visible="(val) => showDiseasePopup = val ? index : false" 
              @close="closeDiseasePopup" 
              @confirm="(disease) => handleDiseaseConfirm(disease, index)" 
            />
           
            <ItemWithImagesCard
              :model-value="item"
              @update:model-value="(data) => update(index, data)"
              :show-title="true"
              title-label="服务项目"
              title-placeholder="请输入服务项目名称"
              description-label="服务详情"
              description-placeholder="请输入服务详情记录"
              :description-rows="3"
              border-color="border-green-300"
              :max-images="9"
            />
          </template>
        </ItemListManager>
        <DoulaBirthRecord />
      </view>
    </view>
  </CollapsibleSection>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useItemManagement } from '@/composables/useItemManagement'
import CollapsibleSection from '@/components/CollapsibleSection.vue'
import ItemListManager from '@/components/ItemListManager.vue'
import ItemWithImagesCard from '@/components/ItemWithImagesCard.vue'
import HospitalDepartmentProjectSelector from '@/components/HospitalDepartmentProjectSelector.vue'
import DiseaseSelector from '@/components/DiseaseSelector.vue'
import DoulaBirthRecord from '@/components/medical-record/DoulaBirthRecord.vue'


interface Props {
  isExpanded: boolean
}

interface Emits {
  (e: 'toggle'): void
}

defineProps<Props>()
defineEmits<Emits>()

const { formData, addHomeCareRecord, removeHomeCareRecord, updateHomeCareRecord } = useItemManagement()

// 获取选择器显示文本
const getSelectorText = (index?: number) => {
  const item = index !== undefined ? formData.value.homeCareRecords?.[index] : formData.value;
  const parts: string[] = [];
  if ((item as any)?.hospital) parts.push((item as any).hospital);
  if ((item as any)?.department) parts.push((item as any).department);
  if ((item as any)?.dept) parts.push((item as any).dept);
  if ((item as any)?.project) parts.push((item as any).project);

  if (parts.length) {
    return parts.join(" / ");
  }
  return "请选择机构/部门/科室/项目组";
};

// 选择器弹窗状态与处理
const showPopup = ref<number | false>(false);
const showDirectoryPopup = (index: number) => {
  showPopup.value = index;
};
const closeDirectoryPopup = () => {
  showPopup.value = false;
};
const handleSelectorConfirm = (data: any, index?: number) => {
  const { hospital, team, department, project } = data;
  if (index !== undefined && index >= 0) {
    // 更新特定项目的医院信息
    const item = formData.value.homeCareRecords?.[index];
    if (item) {
      if (hospital) (item as any).hospital = hospital.title || hospital.name;
      if (team) (item as any).department = team.title || team.name;
      if (department) (item as any).dept = department.title || department.name;
      if (project) {
        (item as any).project = project.title || project.name;
        (item as any).projectId = project.id || project.key;
      }
    }
  } else {
    // 更新全局医院信息
    if (hospital) updateField("hospital", hospital.title || hospital.name);
    if (team) updateField("department", team.title || team.name);
    if (department) updateField("dept", department.title || department.name);
    if (project) {
      updateField("project", project.title || project.name);
      updateField("projectId", project.id || project.key);
    }
  }
  showPopup.value = false;
};

// 疾病选择相关状态
const showDiseasePopup = ref<number | false>(false);

// 疾病选择器相关方法
const showDiseasePopupHandler = (index: number) => {
  showDiseasePopup.value = index;
};

const closeDiseasePopup = () => {
  showDiseasePopup.value = false;
};

// 处理疾病选择确认
const handleDiseaseConfirm = (disease: any, index?: number) => {
  if (index !== undefined && index >= 0) {
    // 更新特定项目的疾病信息
    const item = formData.value.homeCareRecords?.[index];
    if (item) {
      if (disease.customItems) {
        // 处理自定义项目
        const customDiseaseName = disease.customItems.map((item: any) => item.title).join("、");
        (item as any).disease = customDiseaseName;
        (item as any).diseaseId = disease.id;
        (item as any).customDiseaseItems = disease.customItems;
      } else {
        // 处理标准疾病
        (item as any).disease = disease.name;
        (item as any).diseaseId = disease.id;
      }
    }
  } else {
    // 更新全局疾病信息
    if (disease.customItems) {
      const customDiseaseName = disease.customItems.map((item: any) => item.title).join("、");
      updateField("disease", customDiseaseName);
      updateField("diseaseId", disease.id);
      updateField("customDiseaseItems", disease.customItems);
    } else {
      updateField("disease", disease.name);
      updateField("diseaseId", disease.id);
    }
  }
};

// 获取疾病选择器显示文本
const getDiseaseSelectorText = (index?: number) => {
  const item = index !== undefined ? formData.value.homeCareRecords?.[index] : formData.value;
  if ((item as any)?.disease) {
    return (item as any).disease;
  }
  return "请选择疾病（开发中）";
};

// 更新字段方法
const updateField = (field: string, value: any) => {
  console.log("更新字段:", field, value);
  // 这里需要根据实际的store方法来更新字段
  // 假设有一个通用的更新方法
  if (typeof formData.value === "object" && formData.value !== null) {
    (formData.value as any)[field] = value;
  }
};
</script>

<style scoped lang="scss">
.hospital-selector {
  border: 1rpx solid #e5e7eb;
  border-radius: 12rpx;
  background: white;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-bottom: 24rpx;
  
  &:hover {
    border-color: #3b82f6;
  }
  
  &:active {
    opacity: 0.8;
  }
  
  .selector-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 32rpx;
    
    .selector-text {
      font-size: 28rpx;
      color: #374151;
      flex: 1;
    }
    
    .selector-arrow {
      font-size: 24rpx;
      color: #9ca3af;
      margin-left: 16rpx;
      transition: transform 0.2s ease;
    }
  }
  
  &:active .selector-arrow {
    transform: rotate(180deg);
  }
}

.disease-selector {
  border: 1rpx solid #e5e7eb;
  border-radius: 12rpx;
  background: white;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-bottom: 24rpx;
  
  &:hover {
    border-color: #3b82f6;
  }
  
  &:active {
    opacity: 0.8;
  }
  
  .selector-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 32rpx;
    
    .selector-text {
      font-size: 28rpx;
      color: #374151;
      flex: 1;
    }
    
    .selector-arrow {
      font-size: 24rpx;
      color: #9ca3af;
      margin-left: 16rpx;
      transition: transform 0.2s ease;
    }
  }
  
  &:active .selector-arrow {
    transform: rotate(180deg);
  }
}
</style>
